import json
import random

from django import http
from django.contrib.auth import login, authenticate
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render, redirect
from django.urls import reverse
from django_redis import get_redis_connection

from apps.goods.models import SKU
from apps.goods.utils import CookieSecret
from apps.users import constants
from libs.captcha.captcha.captcha import captcha
from meiduo_test.settings.dev import logger
from utils.response_code import RETCODE
from .models import User
# Create your views here.
from django.views import View


class RegisterView(View):
    def get(self,request):

        return render(request,'register.html')

    def post(self,request):

        username=request.POST.get('username')
        password=request.POST.get('password')
        password2=request.POST.get('password2')
        mobile=request.POST.get('mobile')
        sms_code=request.POST.get('msg_code')
        allow=request.POST.get('allow')

        redis_sms_conn=get_redis_connection('sms_code')
        redis_sms=redis_sms_conn.get(mobile)


        if redis_sms is None:
            return render(request, 'register.html', {'sms_code_errmsg': '无效的短信验证码'})

        if sms_code != redis_sms.decode():
            return render(request, 'register.html', {'sms_code_errmsg': '输入短信验证码有误'})

        user = User.objects.create_user(username=username, password=password, mobile=mobile)        # 实现状态保持
        login(request, user)

        # 响应注册结果
        response=redirect(reverse('contents:index'))

        response.set_cookie('username',username,max_age=3600 * 24 * 15)
        return response

#校验用户名重复
class UsernameCountView(View):
    def get(self,request,username):
        count = User.objects.filter(username=username).count()
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'count': count})


#校验手机号重复
class MobileCountView(View):
    def get(self,request,mobile):
        count=User.objects.filter(mobile=mobile).count()
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'count': count})

#生成图像验证码
class ImageCodeView(View):
    def get(self,request,uuid):
        redis_conn=get_redis_connection('verify_image_code')
        text,image=captcha.generate_captcha()

        redis_conn.setex(uuid,constants.IMAGE_CODE_REDIS_EXPIRES,text)
        return http.HttpResponse(image,content_type='image/jpg')

#校验图像验证码，生成短信验证码
class SMSCodeView(View):
    def get(self,request,mobile):
        image_code=request.GET.get('image_code')
        uuid=request.GET.get('image_code_id')
        #1判断图片验证码是否正确
        rimage_code_conn=get_redis_connection('verify_image_code')
        redis_image_code=rimage_code_conn.get(uuid)
        if not redis_image_code:
            return http.JsonResponse({'code': "4002", 'errmsg': '图形验证码失效了'})
        try:
            rimage_code_conn.delete(uuid)
        except Exception as e:
            logger.error(e)


        if (redis_image_code.decode()).lower()!=image_code.lower():
            return http.JsonResponse({'code': "4001", 'errmsg': '输入图形验证码有误'})
        #2.生成随机六位码
        sms_code='%06d' %random.randint(0,999999)
        print(sms_code)
        #3.保存
        rsms_code_conn=get_redis_connection('sms_code')
        rsms_code_conn.setex(mobile,constants.SMS_CODE_REDIS_EXPIRES,sms_code)
        #4.发送

        #5.返回
        return http.JsonResponse({'code': '0', 'errmsg': '发送短信成功'})

#历史记录
class UserBrowseHistory(LoginRequiredMixin,View):
    """
    用户的浏览记录
    """
    def post(self,request):
        """
        保存用户的浏览记录
        :param request:
        :return: JsonResponse
        """
        sku_id=json.loads(request.body.decode())['sku_id']

        redis_client=get_redis_connection('history')
        history=redis_client.lrange(request.user.id,0,-1)
        if  history:
            redis_client.lrem(request.user.id,0,sku_id)
            redis_client.lpush(request.user.id,sku_id)
            redis_client.ltrim(request.user.id,0,4)
        else:
            redis_client.lpush(request.user.id,0,sku_id)

        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK'})

    def get(self,request):
        redis_client=get_redis_connection('history')
        history=redis_client.lrange(request.user.id,0,-1)

        skus=[]
        for category_id in history:
            category_id=int(category_id.decode())

            sku=SKU.objects.get(id=category_id)
            skus.append({
                'id':category_id,
                'name':sku.name,
                'default_image_url':sku.default_image.url,
                'price':int(sku.price)
            })
        return http.JsonResponse({"code": "0","errmsg": "OK",'skus':skus})
        # {
        #     "code": "0",
        #     "errmsg": "OK",
        #     "skus": [
        #         {
        #             "id": 6,
        #             "name": "Apple iPhone 8 Plus (A1864) 256GB 深空灰色 移动联通电信4G手机",
        #             "default_image_url": "http://image.meiduo.site:8888/group1/M00/00/02/CtM3BVrRbI2ARekNAAFZsBqChgk3141998",
        #             "price": "7988.00"
        #         },
        #         ......
        #     ]
        # }

#忘记密码
class FindPassword(View):
    def get(self,request):
        return render(request,'find_password.html')
#1验证用户
class VerifyAccounts(View):
    def get(self,request,username):
        """
        username(路径参数)	用户名
        image_code(查询参数)	图片验证码
        image_code_id(查询参数)	uuid
        :return:
        """
        image_code=request.GET.get('image_code')
        image_code_id=request.GET.get('image_code_id')
        try:
            user=User.objects.get(username=username)
        except:
            """
            status	5000--成功
            5001 图片验证码验证失败
            5004 用户名或手机号不存在
            mobile	用户手机号
            access_token
            """
            return http.JsonResponse({
                "status": 5004,
                "mobile": 0,
                "access_token": ' '

            })
        redis_client=get_redis_connection('verify_image_code')
        redis_data=redis_client.get(image_code_id)

        if redis_data.decode().lower() != image_code.lower():
            print(image_code, redis_data.decode())
            return http.JsonResponse({
                "status": 5001,
                "mobile": 0,
                "access_token": ' '

            })


        mobile = user.mobile
        a=random.randint(0,1999)
        access_token=CookieSecret.dumps(username+'-'+ str(a)+mobile)
        redis_token=get_redis_connection('tokens')
        redis_token.set('token_%d' %user.id,access_token)
        return http.JsonResponse({
            "status": 5000,
            "mobile": mobile,
            "access_token": access_token
        })

#发送短信验证码
class VerifyMobile(View):
    def get(self,request,mobile):
        access_token=request.GET.get('access_token')
        redis_client=get_redis_connection('tokens')
        try:
            user=User.objects.get(mobile=mobile)
            token=redis_client.get('token_%d' %user.id)
        except:
            return http.JsonResponse({
                "status": 5001,
                'message': "该手机号不存在"
            })

        if access_token == token.decode():
            #2.生成随机六位码
            sms_code='%06d' %random.randint(0,999999)
            #3.保存
            rsms_code_conn=get_redis_connection('sms_code')
            rsms_code_conn.setex(mobile,constants.SMS_CODE_REDIS_EXPIRES,sms_code)
            print(sms_code)
            return http.JsonResponse({
                "status": 5000,
                'message': "发送消息成功，请注意查收"
            })
        else:
            return http.JsonResponse({
                "status": 5001,
                'message': "token错误"
            })

#校验短信验证码
class VerifySmscode(View):
    def get(self,request,mobile):
        sms_code=request.GET.get('sms_code')
        redis_client=get_redis_connection('sms_code')
        try:
            data=redis_client.get(mobile)
            user=User.objects.get(mobile=mobile)
        except:
            return http.JsonResponse({
            "status": 5004,
            "user_id": '',
            "access_token": ''
        })
        redis_token=get_redis_connection('tokens')
        access_token=redis_token.get('token_%d' %user.id)
        if data.decode()==sms_code:
            return http.JsonResponse({
                    "status": 5000,
                    "user_id": user.id,
                    "access_token": access_token.decode() #怎么获得同一个页面的另一个请求的参数
                })
        else:
            return http.JsonResponse({
                    "status": 5001,
                    "user_id": '',
                    "access_token": ''
                })

#修改密码
class NewPwd(View):
    def post(self,request,user_id):
        print(user_id)
        """
        user_id(查询参数)	int	是	用户名id
        password(json参数)	str	是	新密码
        password2(json参数)	str	是	再次输入密码
        access_token(json参数)	str	是	access_token(校验token值)
        :param request:
        :return:
        """

        data=json.loads(request.body.decode())
        password=data.get('password')
        password2=data.get('password2')
        access_token=data.get('access_token')
        try:
            user=User.objects.get(id=user_id)
        except:
            return http.JsonResponse({
                "status": 5002,
                'message': "user_id错误!"
            })
        redis_token = get_redis_connection('tokens')
        token = redis_token.get('token_%d' % user.id)
        if access_token != token.decode():
            return http.JsonResponse({
                "status": 5001,
                'message': "token错误!"
            })

        user.set_password(password)
        user.save()
        return http.JsonResponse({
            "status": 5000,
            'message': "密码修改成功!"
        })






